// app.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const config = require('./config'); // 引入配置文件


const app = express();
const port = config.server.port || 3000;

//配置解析表单数据中间件
app.use(express.urlencoded({extended: false}))

const userRouter = require('./router/user');
const foodRouter = require('./router/food');
const bookRouter = require('./router/book');
const guideRouter = require('./router/guide');
const videoRouter = require('./router/video');
const communityRouter = require('./router/community');
const dailyRouter = require('./router/daily');
const uploadRouter = require('./router/upload');
const chatRouter = require('./router/chat');


const corsOptions = {
    origin: ['http://localhost:3301', 'http://localhost:5173'], // 允许的源
    credentials: true, // 允许发送凭据
};
app.use(bodyParser.json());
app.use(cors(corsOptions));// 允许跨域
app.use('/uploads', express.static(__dirname + '/uploads'))

// 响应数据的中间件,绑定到全局res上
app.use(function (req, res, next) {
    // status = true 为成功； status = false 为失败； 默认将 status 的值设置为 false，方便处理失败的情况
    res.cc = function (err, status = false) {
        res.send({
            // 状态
            status,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            message: err instanceof Error ? err.message : err,
        });
    };
    next();
});


//路由
app.use('/user', userRouter);
app.use('/food', foodRouter);
app.use('/book', bookRouter);
app.use('/guide', guideRouter);
app.use('/video', videoRouter);
app.use('/community', communityRouter);
app.use('/daily', dailyRouter);
app.use('/chat', chatRouter);
app.use('', uploadRouter);


app.listen(port, () => {
    console.log(`服务器正在运行 http://${config.server.host}:${port}`);
});
